package com.mobileares.midp.widgets.client.pop;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Created by IntelliJ IDEA.
 * User: Tom
 * Date: 2011-4-2
 * Time: 16:33:20
 * To change this template use File | Settings | File Templates.
 */
public class PopHelper {
    private static void initPopStyle(Widget widget) {
        widget.getElement().getStyle().setPosition(Style.Position.ABSOLUTE);
        widget.getElement().getStyle().setLeft(0, Style.Unit.PX);
        widget.getElement().getStyle().setTop(0, Style.Unit.PX);
    }

    public static void show(Widget widget) {
        RootPanel.get().add(widget);
    }

    public static void afterHidden(Widget widget) {
        RootPanel.get().remove(widget);
    }

    public static void center(Widget widget) {


//        int winWidth = Window.getClientWidth();
//        int winHeight = Window.getClientHeight();
//        int width = Math.max(Document.get().getScrollWidth(), winWidth);
//        int height = Math.max(Document.get().getScrollHeight(), winHeight);
        show(widget);
        initPopStyle(widget);
        int left = (Window.getClientWidth() - widget.getOffsetWidth()) >> 1;
        int top = (Window.getClientHeight() - widget.getOffsetHeight()) >> 1;
        setPopupPosition(widget, Math.max(Window.getScrollLeft() + left, 0), Math.max(
                Window.getScrollTop() + top, 0));
    }

    public static void hidden(Widget widget) {
        afterHidden(widget);
    }

    private static void setPopupPosition(Widget widget, int left, int top) {
        // Account for the difference between absolute position and the
        // body's positioning context.
        left -= Document.get().getBodyOffsetLeft();
        top -= Document.get().getBodyOffsetTop();

        // Set the popup's position manually, allowing setPopupPosition() to be
        // called before show() is called (so a popup can be positioned without it
        // 'jumping' on the screen).
        Element elem = widget.getElement();
        elem.getStyle().setPropertyPx("left", left);
        elem.getStyle().setPropertyPx("top", top);
    }


}
